<template>
	<view class="custom-upload">
		<view class="upload-list">
			<view v-for="(item, index) in fileList" :key="index" class="upload-item">
				<image :src="item.url" mode="aspectFill" class="upload-image" @click="previewImage(index)" />
				<view class="delete-icon" @click.stop="handleDelete(index)">
					<text class="iconfont icon-close"></text>
				</view>
				<view v-if="item.status === 'uploading'" class="upload-progress">
					<progress :percent="item.progress" stroke-width="4" />
				</view>
			</view>

			<view v-if="fileList.length < maxCount" class="upload-btn" :style="customStyle" @click="chooseImage">
				<image src="/static/images/resume/上传.svg" class="upload-icon" />
				<text class="upload-text">上传图片</text>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		uploadImage
	} from '@/api/user'; // 引入你的上传接口

	const props = defineProps({
		fileList: {
			type: Array,
			default: () => []
		},
		maxCount: {
			type: Number,
			default: 9
		},
		// 新增：是否自动上传
		autoUpload: {
			type: Boolean,
			default: true
		}
	});

	const emit = defineEmits(['afterRead', 'delete', 'uploadSuccess', 'uploadFail']);

	const customStyle = {
		width: '190rpx',
		height: '190rpx',
		background: '#F6F6F6',
		borderRadius: '20rpx',
		display: 'flex',
		flexDirection: 'column',
		alignItems: 'center',
		justifyContent: 'center'
	};

	const chooseImage = () => {
		const remaining = props.maxCount - props.fileList.length;
		if (remaining <= 0) {
			return uni.showToast({
				title: `最多只能上传${props.maxCount}张图片`,
				icon: 'none'
			});
		}

		uni.chooseImage({
			count: remaining,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: async (res) => {
				if (res.tempFiles.length > 0) {
					// 触发选择文件事件
					emit('afterRead', {
						file: res.tempFiles.length === 1 ? res.tempFiles[0] : res.tempFiles
					});

					// 如果开启自动上传
					if (props.autoUpload) {
						const files = Array.isArray(res.tempFiles) ? res.tempFiles : [res.tempFiles];
						await uploadFiles(files);
					}
				}
			},
			fail: (err) => {
				let errMsg = '选择图片失败';
				if (err.errMsg.includes('cancel')) {
					errMsg = '已取消选择';
				}
				uni.showToast({
					title: errMsg,
					icon: 'none'
				});
			}
		});
	};

	// 新增：上传文件方法
	const uploadFiles = async (files) => {
		try {
			const uploadTasks = files.map(file => {
				// 添加到文件列表，显示上传状态
				const fileItem = {
					url: file.path,
					name: file.name || '未命名文件',
					status: 'uploading',
					progress: 0
				};
				emit('afterRead', {
					file: fileItem
				});

				// 执行上传
				return uploadImage(file, {
					onUploadProgress: (progressEvent) => {
						const percent = Math.round((progressEvent.loaded * 100) / progressEvent
							.total);
						fileItem.progress = percent;
						// 这里可以触发一个更新事件
						emit('uploadProgress', {
							file: fileItem,
							progress: percent
						});
					}
				});
			});

			const results = await Promise.all(uploadTasks);

			results.forEach((res, index) => {
				if (res.code === 200) {
					emit('uploadSuccess', {
						url: res.data.url,
						originFile: files[index]
					});
				} else {
					emit('uploadFail', {
						file: files[index],
						error: res.message
					});
				}
			});

			return results;
		} catch (error) {
			emit('uploadFail', {
				error: error.message
			});
			throw error;
		}
	};

	const handleDelete = (index) => {
		emit('delete', index);
	};

	const previewImage = (index) => {
		uni.previewImage({
			current: props.fileList[index].url,
			urls: props.fileList.map(item => item.url)
		});
	};
</script>

<style lang="scss" scoped>
	.custom-upload {
		.upload-list {
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx;

			.upload-item {
				position: relative;
				width: 190rpx;
				height: 190rpx;
				border-radius: 20rpx;
				overflow: hidden;

				.upload-image {
					width: 100%;
					height: 100%;
				}

				.delete-icon {
					position: absolute;
					right: 10rpx;
					top: 10rpx;
					width: 50rpx;
					height: 42.61rpx;
					background: rgba(0, 0, 0, 0.5);
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;

					.iconfont {
						color: #fff;
						font-size: 20rpx;
					}
				}

				.upload-progress {
					position: absolute;
					bottom: 0;
					left: 0;
					right: 0;
					background: rgba(0, 0, 0, 0.5);
					padding: 10rpx;
					color: #fff;
				}
			}

			.upload-btn {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;

				.upload-icon {
					width: 60rpx;
					height: 60rpx;
					margin-bottom: 20rpx;
				}

				.upload-text {
					font-size: 24rpx;
					color: #999;
				}
			}
		}
	}
</style>